const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')
const { formatTime } = require('../../utils/util')

Page({
  data: {
    coach: {},
    coachId: null,
    loading: true,
    selectedCourse: null
  },

  onLoad(options) {
    this.setData({ coachId: options.id })
    this.loadCoachDetail()
  },

  async loadCoachDetail() {
    try {
      const res = await API.coachDetail(3)
      console.log('res====',res)
      res.avatar = pathUrl + res.avatar
      this.setData({ coach: res })
    } catch (error) {
      console.error('加载教练详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      // 所有数据加载完成后隐藏loading
      this.checkIfAllLoaded()
    }
  },

  // 检查是否所有数据都已加载完成
  checkIfAllLoaded() {
    // 检查是否所有必需数据都已加载
    const hasCoach = Object.keys(this.data.coach).length > 0
    const hasCourses = this.data.courses !== undefined
    const hasReviews = this.data.reviews !== undefined
    
    if (hasCoach && hasCourses && hasReviews) {
      setTimeout(() => {
        this.setData({ loading: false })
      }, 500) // 添加一点延迟，避免页面闪烁
    }
  },

  contactCoach() {
    // 联系教练逻辑
    wx.showActionSheet({
      itemList: ['微信', '拨打电话'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.setClipboardData({
            data: this.data.coach.wechat,   // 你的微信号
            success() {
              wx.showToast({
                title: '微信号已复制，请去微信添加',
                icon: 'none'
              })
            }
          })
        } else if (res.tapIndex === 1) {
          // 拨打电话
          wx.makePhoneCall({
            phoneNumber: this.data.coach.phoneNo
          })
        }
      }
    })
  },

  goToBooking() {
    wx.navigateTo({
      url: '/pages/coach-booking/coach-booking?item='+JSON.stringify(this.data.coach),
    })
    // let form = this.data.coach;
    // API.coachBooking({coachId:form.id,coachName:form.name,location:form.location}).then(res=>{
    //   wx.showToast({
    //     title: '预约成功',
    //     type:'success'
    //   })
    //   setTimeout(() => {
    //     wx.navigateBack();
    //   }, 500) // 添加一点延迟，避免页面闪烁
      
    // }).catch(err=>{
    //   wx.showToast({
    //     title: '预约失败',
    //     icon: 'none'
    //   })
    // })
  },

  previewImage(e) {
    const { images, current } = e.currentTarget.dataset
    wx.previewImage({
      urls: images,
      current: images[current]
    })
  },

  onShareAppMessage() {
    return {
      title: `网球教练-${this.data.coach.name}`,
      path: `/pages/coach-detail/coach-detail?id=${this.data.coachId}`,
      imageUrl: this.data.coach.avatar
    }
  }
})